<?php

namespace common\sms\yuntongxun;

use common\sms\SenderInterface;
use common\sms\SenderTrait;

class Sender implements SenderInterface
{
    use SenderTrait;

    // API类
    public $rest;

    // 验证码短信模板ID
    private $tplID;

    //请求地址
    private $serverIP = 'app.cloopen.com';

    //请求端口
    private $serverPort = '8883';

    //REST版本号
    private $softVersion = '2013-12-26';

    public function init($config)
    {
        require_once 'CCPRestSmsSDK.php';
        $required = ['sid', 'token', 'app_id', 'tpl_id'];
        if (!$this->hasKeys($config, $required)){
            return false;
        }

        $rest = new \REST($this->serverIP, $this->serverPort, $this->softVersion);
        $rest->setAccount($config['sid'], $config['token']);
        $rest->setAppId($config['app_id']);
        $this->rest = $rest;
        $this->tplID = $config['tpl_id'];
        return true;
    }

    public function checkTemplate($template)
    {
        return isset($template['id']);
    }

    public function send($mobile, $template)
    {
        $this->setErrorMsg('');
        $data = isset($template['data']) ? $template['data'] : [];
        // 发送模板短信
        $result = $this->rest->sendTemplateSMS($mobile, $data, $template['id']);
        if ($result == null) {
            $this->setErrorMsg('result error!');
            return false;
        }
        if ($result->statusCode != 0) {
            $this->setErrorMsg($result->statusMsg);
            return false;
        } else {
            return true;
        }
    }

    public function sendValidMsg($mobile, $code, $m)
    {
        return $this->send($mobile, ['id' => $this->tplID, 'data' => [$code, $m]]);
    }
}